import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _map from "lodash/map";
import _isEmpty from "lodash/isEmpty";

var _dec, _class;

import React from 'react';
import { Layout } from 'antd';
import { Bind } from 'lodash-decorators';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { Switch, Route, Redirect } from 'dva/router';
import dynamic from 'dva/dynamic';
import LoadingBar from "../components/NProgress/LoadingBar";
import getTabRoutes from "../components/Router";
import webSocketManagener from "../utils/webSoket";
import { getAccessToken, getRefreshToken, getCurrentOrganizationId, getCurrentRole, getCurrentLanguage } from "../utils/utils";
import { tabListen } from "../utils/menuTab";
import NotFound from "../routes/Exception/404";
import "./PubLayout.less";
var Content = Layout.Content;

var EMPTY_ROUTE = function EMPTY_ROUTE() {
  return null;
};

var showStyle = {};
/**
 * 菜单数据结构改变 只有菜单有path,目录没有path
 * 所有的菜单必须有 服务前缀 `/服务前缀/...功能集合/功能/...子功能`
 * 根据菜单取得重定向地址.
 */

var getRedirect = function getRedirect(item) {
  var redirectData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  if (item && item.children) {
    // 目录
    for (var i = 0; i < item.children.length; i++) {
      getRedirect(item.children[i], redirectData);
    }

    return redirectData;
  } else if (item && item.path) {
    // 菜单
    var menuPaths = item.path.split('/');

    if (!menuPaths[0]) {
      menuPaths = menuPaths.slice(1, menuPaths.length);
    }

    var menuPath = '';

    var _loop = function _loop(_i) {
      menuPath += "/".concat(menuPaths[_i]);
      var from = menuPath;
      var to = "".concat(menuPath, "/").concat(menuPaths[_i + 1]);
      var exist = redirectData.some(function (route) {
        return route.from === from;
      });

      if (!exist) {
        redirectData.push({
          from: from,
          to: to
        });
      }
    };

    for (var _i = 0; _i < menuPaths.length - 1; _i++) {
      _loop(_i);
    }
  }
};

var PublicLayout = (_dec = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(PublicLayout, _React$Component);

  var _super = _createSuper(PublicLayout);

  function PublicLayout() {
    var _this;

    _classCallCheck(this, PublicLayout);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _this.getBashRedirect = function () {
      // According to the url parameter to redirect
      // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
      var urlParams = new URL(window.location.href);
      var redirect = urlParams.searchParams.get('redirect'); // Remove the parameters in the url

      if (redirect) {
        urlParams.searchParams.delete('redirect');
        window.history.replaceState(null, 'redirect', urlParams.href);
      } else {
        var _this$props$routerDat = _this.props.routerData,
            routerData = _this$props$routerDat === void 0 ? {} : _this$props$routerDat; // get the first authorized route path in routerData
        // const authorizedPath = Object.keys(routerData).find(
        //   item => check(routerData[item].authority, item) && item !== '/'
        // );

        var authorizedPath = Object.keys(routerData).find(function (item) {
          return item !== '/';
        });
        return authorizedPath;
      }

      return redirect;
    };

    return _this;
  }

  _createClass(PublicLayout, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          currentUser = _this$props.currentUser;

      if (currentUser) {
        dispatch({
          type: 'global/pubLazyInit',
          payload: {
            organizationId: getCurrentOrganizationId(),
            language: currentUser.language,
            roleId: getCurrentRole().id
          }
        }).then(function () {
          // 不需要初始化菜单成功
          tabListen();
        });
      } // 设置中文时的表单样式处理


      var language = getCurrentLanguage();

      if (language && language !== 'zh_CN') {
        document.body.className = 'global-layout';
      } // 清除首屏loading


      var loader = document.querySelector('#loader-wrapper');

      if (loader) {
        document.body.removeChild(loader); // 设置默认页面加载动画

        dynamic.setDefaultLoadingComponent(function () {
          return /*#__PURE__*/React.createElement(LoadingBar, null);
        });
      }

      window.accessToken = window.accessToken || getAccessToken('access_token');
      window.refreshToken = window.refreshToken || getRefreshToken('refresh_token');
      this.refreshTimer = setInterval(function () {
        var accessToken = getAccessToken('access_token'); // const refreshToken = getRefreshToken('refresh_token');

        var windowToken = window.accessToken; // const windowRefreshToken = window.refreshToken;

        if (accessToken && windowToken && windowToken !== accessToken) {
          window.location.reload();
        }
      }, 3000);
      this.receiveWebSocketMsg();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      clearInterval(this.refreshTimer); // 关闭 webSocket 连接

      webSocketManagener.destroyWebSocket();
    }
  }, {
    key: "receiveWebSocketMsg",
    value: function receiveWebSocketMsg() {
      var _this2 = this;

      webSocketManagener.initWebSocket();
      webSocketManagener.addListener('client', function (messageData) {
        var _this2$props = _this2.props,
            dispatch = _this2$props.dispatch,
            count = _this2$props.count;
        var message = messageData.message;
        var messageJson = _isEmpty(message) ? undefined : JSON.parse(message);

        if (!_isEmpty(messageJson)) {
          var tenantId = messageJson.tenantId,
              number = messageJson.number;
          var newCount = count;

          if (tenantId === 0) {
            newCount = Number(count) + Number(number);
          } else if (tenantId === getCurrentOrganizationId()) {
            newCount = Number(count) + Number(number);
          }

          dispatch({
            type: 'global/saveNotices',
            payload: {
              count: newCount
            }
          });
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          currentUser = _this$props2.currentUser,
          routerData = _this$props2.routerData,
          _this$props2$menu = _this$props2.menu,
          menu = _this$props2$menu === void 0 ? [] : _this$props2$menu,
          activeTabKey = _this$props2.activeTabKey,
          tabs = _this$props2.tabs;
      var redirectData = [{
        from: '/',
        to: '/workplace'
      }]; // 根目录需要跳转到工作台

      menu.forEach(function (item) {
        getRedirect(item, redirectData);
      });
      var bashRedirect = this.getBashRedirect();
      var layout = /*#__PURE__*/React.createElement(Layout, {
        style: {
          height: '100vh',
          overflow: 'hidden'
        }
      }, /*#__PURE__*/React.createElement(Switch, null, _map(redirectData, function (item) {
        return /*#__PURE__*/React.createElement(Redirect, {
          key: item.from,
          exact: true,
          from: item.from,
          to: item.to
        });
      }), bashRedirect ? /*#__PURE__*/React.createElement(Redirect, {
        exact: true,
        from: "/",
        to: bashRedirect
      }) : null, menu.length === 0 ? null : /*#__PURE__*/React.createElement(Route, {
        render: EMPTY_ROUTE
      })), _map(tabs, function (pane) {
        return activeTabKey === pane.key && /*#__PURE__*/React.createElement(Content, {
          key: pane.key,
          className: "page-container",
          style: showStyle
        }, getTabRoutes({
          pane: pane,
          routerData: routerData,
          NotFound: NotFound,
          menu: menu,
          activeTabKey: activeTabKey
        }));
      }));
      return /*#__PURE__*/React.createElement(DocumentTitle, {
        title: currentUser.title || ''
      }, layout);
    }
  }]);

  return PublicLayout;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "receiveWebSocketMsg", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "receiveWebSocketMsg"), _class.prototype)), _class));
export default connect(function (_ref) {
  var user = _ref.user,
      _ref$global = _ref.global,
      global = _ref$global === void 0 ? {} : _ref$global;
  return {
    menu: global.menu,
    routerData: global.routerData,
    currentUser: user.currentUser,
    activeTabKey: global.activeTabKey,
    tabs: global.tabs,
    language: global.language
  };
})(PublicLayout);